/**
 * Created by yanwc on 2016/9/18.
 */
/**
 * 登录认证服务
 */
'use strict';

angular.module('app').factory('AuthService',
    ["$http","$q","$window","$state",function ($http, $q, $window,$state) {
        var userInfo;
        function login(userName, password) {
            var deferred = $q.defer();
            $http({
                    url: "/login",
                    data: {
                        username: userName,
                        password: password
                    },
                    method: 'POST',
                    headers:{'Content-Type':'application/x-www-form-urlencoded'},
                    transformRequest:function(obj){
                        var str=[];
                        for(var p in obj){
                            str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
                        }
                        return str.join("&");
                    }
                }
            ).then(function (result) {
                    if(!!!result.data && !result.data.success){
                        deferred.reject(result.data.message);
                    }else{
                        $window.localStorage["userInfo"] = JSON.stringify(result.data);
                        deferred.resolve(result.data);
                    }
                }, function (error) {
                    deferred.reject(error);
                });

            return deferred.promise;
        }
        //获取当前用户
        function getCurrentUser(){
            var user = $window.localStorage["userInfo"];
            if(user == null){
                //跳转到登陆页面
                $state.go("access.signup");
            }else{
                return user;
            }
        }
        //返回接口
        return {
            login: login,
            getCurrentUser:getCurrentUser
        };
    }]);